import axios from "axios";
import { ElNotification } from "element-plus";

const instance = axios.create({
  baseURL: "http://localhost:8088/api",
  timeout: 5000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

instance.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem("token");
    if (token && token != null && token != "null") {
      config.headers.Authorization = "Bearer " + token;
    }
    return config;
  },
  (err) => {
    console.log("请求有问题", err);
  }
);


instance.interceptors.response.use(
  (res) => {
    console.log(res.config.url, res);
    if (
      res.config.responseType === "blob" ||
      res.config.responseType === "arraybuffer"
    ) {
      return res;
    }
    const { code, data, msg } = res.data;
    return new Promise((resolve, reject) => {
      if (res.status === 200) {
        if (data && code === "00000") {
           resolve(data)
        } else {
          ElNotification({
            title: "请求失败",
            message: code + ":" + msg,
            type: "error",
          });
          reject(msg)
        }
      } else {
        ElNotification({
          title: "请求失败",
          message: "status:" + res.status + "," + msg,
          type: "error",
        })
      }
    });
  },
  (err) => {
    console.log("返回失败", err.response);
    if (err.response.data.code === "A0230") {
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      location.reload();
      router.replace({ path: "/login" });
    } else {
      ElNotification({ title: "请求失败", message: err, type: "error" });
    }
  }
);

export default instance;
